import 'package:graphql/client.dart';

class GQLClient {
  // 'https://api.github.com/graphql',
  // 'http://localhost:7777/graphql',
  // 'https://apiv1.tianfulei.cn/recover/graphql',
  final String gqladdress;
  // 'ws://localhost:7777/graphql'
  // 'wss://apiv1.tianfulei.cn/recoverwss/graphql'
  final String websocketEndpoint;
  // 'cb08e671-6414-4d0a-bcf6-b334e79c9e8e'
  final String token;

  late HttpLink _httpLink;
  late AuthLink _authLink;
  late Link _link;
  late GraphQLClient client;

  GQLClient(
      {required this.gqladdress,
      required this.websocketEndpoint,
      required this.token}) {
    _httpLink = HttpLink(gqladdress);
    _authLink = AuthLink(
      headerKey: 'Accesstoken',
      getToken: () async => token,
    );

    _link = _authLink.concat(_httpLink);

    if (websocketEndpoint != null) {
      final _wsLink = WebSocketLink(websocketEndpoint);
      _link = Link.split((request) => request.isSubscription, _wsLink, _link);
    }

    client = GraphQLClient(
      cache: GraphQLCache(),
      link: _link,
    );
  }

  void listenSysEvent(void Function(QueryResult) onData) {
    final subscriptionDocument = gql(
      r'''
      subscription{
        eventPublished(name:""){
          id
          name
          data
        }
      }
    ''',
    );
    // graphql/client.dart usage
    var subscription = client.subscribe(
      SubscriptionOptions(document: subscriptionDocument),
    );
    subscription.listen(onData);
  }

  Stream<QueryResult> listenMachinePacket(
      String sn, void Function(QueryResult) onData) {
    final subscriptionDocument = gql(
      r'''
        subscription($sn:String!){
          ecgMachineMonitor(sn:$sn) {
            id
            ts
            tp
            mc
            sn
            pt
            pk
            rd
            sq
          }
        }
    ''',
    );
    // graphql/client.dart usage
    var subscription = client.subscribe(
      SubscriptionOptions(document: subscriptionDocument, variables: {
        'sn': sn,
      }),
    );
    // subscription.listen(onData);
    return subscription;
  }

  Stream<QueryResult> listenRecordPacket(
      String rd, void Function(QueryResult) onData) {
    final subscriptionDocument = gql(
      r'''
        subscription($rd:String!){
          ecgRecordMonitor(rd:$rd) {
            id
            ts
            tp
            mc
            sn
            pt
            pk
            rd
            sq
          }
        }
    ''',
    );
    // graphql/client.dart usage
    var subscription = client.subscribe(
      SubscriptionOptions(document: subscriptionDocument, variables: {
        'rd': rd,
      }),
    );
    // subscription.listen(onData);
    return subscription;
  }
}
